package com.liuhung.ash.security.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.liuhung.base.web.BaseAction;
import com.liuhung.ash.security.entity.Model;
import com.liuhung.ash.security.entity.Users;
import com.liuhung.ash.security.service.ModelService;
import com.liuhung.ash.security.service.UsersService;

/**
 * 
 * <br>
 * <b>功能：</b>ModelController<br>
 */
@Controller
@RequestMapping
public class MainController extends BaseAction {
	private final static Logger log = Logger.getLogger(MainController.class);

	// Servrice start
	@Autowired(required = false)
	// 自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	UsersService usersService;
	
	@Autowired(required=false)
	ModelService modelService;
	
	@RequestMapping("/admin/login")
	public ModelAndView login(HttpServletRequest request,Model model,final RedirectAttributes redirectAttributes)
			throws Exception {
		Map<String, Object> context = getRootMap();
		String error=request.getParameter("error")!=null?request.getParameter("error"):"0";
		if(error.equals("1"))
		{
			redirectAttributes.addFlashAttribute("message", "登录身份已失效!请重新登录!");
		}
		return forword("login", context);
	}
	@RequestMapping(value = "/admin/main", method = RequestMethod.POST)
	public ModelAndView logining(Users users, HttpServletRequest request,
			HttpServletResponse response,org.springframework.ui.Model Uimodel,final RedirectAttributes redirectAttributes) throws Exception {
		Map<String, Object> context = getRootMap();
		Subject curUser = SecurityUtils.getSubject();
		log.info(users.getUsername()+users.getPassword());
		UsernamePasswordToken token = new UsernamePasswordToken(
				users.getUsername(), users.getPassword());
		token.setRememberMe(true);
		try {
			curUser.login(token);
			if(curUser.isAuthenticated()){
				log.info(users.getUsername() + "登陆 成功。");
				Users users2 =usersService.findUserByUserName(users.getUsername());
	            setLocalUser(users2, request);
	            List<Model> models=this.getModels(request);
	            Uimodel.addAttribute("ip", getIpAddr(request));;
				log.info(getIpAddr(request) +"登陆)------------成功。");
	            return forword("main", context);
			}
			else
			{	redirectAttributes.addFlashAttribute("message", "登录失败，请检查密码是否正确。");
				return new ModelAndView("redirect:login");
			}

		} catch (AuthenticationException e) {
		token.clear();
		if(e instanceof IncorrectCredentialsException)
		{
		log.warn(users.getUsername()+"登陆失败。失败原因："+e.getMessage());
		redirectAttributes.addFlashAttribute("message", "认证无法通过，请检查密码是否正确。");
		}
		else {
		log.warn(users.getUsername()+"登陆失败。失败原因："+e.getMessage());
		redirectAttributes.addFlashAttribute("message",e.getMessage() );
		}
		}
		redirectAttributes.addFlashAttribute("username",users.getUsername() );
		return new ModelAndView("redirect:login");
		}
	@RequiresUser
	@RequestMapping(value = "/admin/logout")
	public ModelAndView logout(HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		setLocalUserNull(request);
		return forword("redirect:login", context);
	}
	@RequestMapping(value = "/noRole")
	public ModelAndView noRole(HttpServletRequest request)
	{
		System.out.println("进入没有权限页面");
		return new ModelAndView("/main/noRole");
	}

}
